import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
;(window as any).ipcRenderer = ipcRenderer
// Custom APIs for renderer
const api = {}
// 存储事件监听器的映射
const listeners = new Map()
// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
	try {
		// contextBridge.exposeInMainWorld('electron', electronAPI)
		// contextBridge.exposeInMainWorld('api', api)
		contextBridge.exposeInMainWorld('ipcRenderer', {
			// 安全的事件监听方法
			on: (channel, callback) => ipcRenderer.on(channel, callback),
			// on: (channel, callback) => {
			// 	if (!['window-maximize-changed'].includes(channel)) return

			// 	// 确保传递完整的事件参数
			// 	ipcRenderer.on(channel, (event, ...args) => {
			// 		callback(event, ...args)
			// 	})
			// },

			// 安全的移除监听器方法
			removeAllListeners: (channel) => {
				if (!listeners.has(channel)) return

				listeners.get(channel).forEach((listener) => {
					ipcRenderer.removeListener(channel, listener)
				})
				listeners.delete(channel)
			},

			// 其他IPC方法
			send: (channel, data) => ipcRenderer.send(channel, data),
			invoke: (channel, data) => ipcRenderer.invoke(channel, data)
		})
	} catch (error) {
		console.error(error)
	}
} else {
	// @ts-ignore (define in dts)
	window.electron = electronAPI
	// @ts-ignore (define in dts)
	window.api = api
}
